let gameInfo = {
    roomId: null,
    thisUserId: null,
    thatUserId: null,
    isWhite: true,
}

//////////////////////////////////////////////////
// 设定界面显示相关操作
//////////////////////////////////////////////////

function setScreenText(me) {
    let screen = document.querySelector('#screen');
    if (me) {
        screen.innerHTML = "轮到你落子了!";
        screen.style.color = "red";
    } else {
        screen.innerHTML = "轮到对方落子了!";
        screen.style.color = "black";
    }
}

//////////////////////////////////////////////////
// 初始化 websocket
//////////////////////////////////////////////////
// TODO

let websocket = new WebSocket('ws://'+location.host+'/game');
// 获取 websocket 连接
websocket.onopen = function () {
    console.log("建立连接!");
}

websocket.onclose = function () {
    console.log("连接关闭!");
    location.replace("/game_hall.html");
}

websocket.onerror = function () {
    console.log("连接异常关闭!");
}

window.onbeforeunload = function () {
    console.log("监测页面状态关闭/刷新")
    websocket.close();
}

// 监听页面隐藏事件（适用于现代浏览器）
window.onpagehide = function () {
    console.log('页面隐藏，关闭 WebSocket 连接');
    websocket.close();
}

// 处理后端传来的信息
websocket.onmessage = function (event) {
    let result = JSON.parse(event.data);
    console.log(result);
    if (result.ok || result.roomId != null) {
        gameInfo.roomId = result.roomId;
        gameInfo.thisUserId = result.thisUser.userId;
        gameInfo.thatUserId = result.thatUser.userId;
        gameInfo.isWhite = (result.white == result.thisUser.userId);
        // 初始化棋盘
        initGame();
        // 设置下方轮到谁下棋了, 这个文本
        setScreenText(gameInfo.isWhite);
    }else {
        alert("您当前未登录, 请前去登陆!");
        location.assign("/login.html");
    }
}


//////////////////////////////////////////////////
// 初始化一局游戏
//////////////////////////////////////////////////
function initGame() {
    // 是我下还是对方下. 根据服务器分配的先后手情况决定
    let me = gameInfo.isWhite;
    // 游戏是否结束
    let over = false;
    let chessBoard = [];
    //初始化chessBord数组(表示棋盘的数组)
    for (let i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }
    let chess = document.querySelector('#chess');
    let context = chess.getContext('2d');
    context.strokeStyle = "#BFBFBF";
    // 背景图片
    let logo = new Image();
    logo.src = "image/sky.jpeg";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
    }

    // 绘制棋盘网格
    function initChessBoard() {
        for (let i = 0; i < 15; i++) {
            context.moveTo(15 + i * 30, 15);
            context.lineTo(15 + i * 30, 430);
            context.stroke();
            context.moveTo(15, 15 + i * 30);
            context.lineTo(435, 15 + i * 30);
            context.stroke();
        }
    }

    // 绘制一个棋子, me 为 true
    function oneStep(i, j, isWhite) {
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        if (!isWhite) {
            gradient.addColorStop(0, "#0A0A0A");
            gradient.addColorStop(1, "#636766");
        } else {
            gradient.addColorStop(0, "#D1D1D1");
            gradient.addColorStop(1, "#F9F9F9");
        }
        context.fillStyle = gradient;
        context.fill();
    }

    chess.onclick = function (e) {
        if (over) {
            return;
        }
        if (!me) {
            return;
        }
        let x = e.offsetX;
        let y = e.offsetY;
        // 注意, 横坐标是列, 纵坐标是行
        let col = Math.floor(x / 30);
        let row = Math.floor(y / 30);
        if (chessBoard[row][col] == 0) {
            // TODO 发送坐标给服务器, 服务器要返回结果
            send(row,col);

            // oneStep(col, row, gameInfo.isWhite);
            // chessBoard[row][col] = 1;
        }
    }

    // 给服务器发送自己下棋的坐标
    function send(row,col) {
        let response = {
            chess: true,
            userId: gameInfo.thisUserId, // 要发送自己的坐标, 所以是 thisUserId
            white: gameInfo.isWhite, // 获取 已经设置好的 白子的信息
            row:row,
            col:col
        };
        // 通过 websocket 发送给后端的 ChessRequest
        websocket.send(JSON.stringify(response));
    }


    // 发送好之后, 接收响应
    websocket.onmessage = function (event) {
        let result = JSON.parse(event.data);
        console.log(result);
        if (result != null && result.chess) {
            // 1. 绘制棋子
            // 显示横坐标, 再试纵坐标, 与行和列正好相反

            if (!result.flag) {
                if (result.userId == gameInfo.thisUserId) {
                    // 是我下的棋, 绘制我棋子的颜色'
                    oneStep(result.col, result.row, gameInfo.isWhite);
                } else if (result.userId == gameInfo.thatUserId) {
                    // 对手下的棋子, 绘制对手棋子的颜色
                    oneStep(result.col, result.row, !gameInfo.isWhite);
                } else {
                    // 错误响应
                    console.log(result.userId);
                    return;
                }
            }

            // 该位置已经有棋子, 占位置
            chessBoard[result.row][result.col] = 1;

            // 交换下棋顺序
            me = !me;
            setScreenText(me);

            // 2. 判断胜负, 判断游戏是否结束!
            if (result.winner != 0) {
                let screen = document.querySelector("#screen");
                if (result.winner == -1) {
                    screen.innerHTML = "牛逼,平局了!";
                }else if (result.winner == gameInfo.thisUserId) {
                    if (result.flag) {
                        screen.innerHTML = "对方掉线, 你赢了";
                    }else {
                        screen.innerHTML = "恭喜,你赢了!";
                    }
                }else if (result.winner == gameInfo.thatUserId) {
                    screen.innerHTML = " 很遗憾, 你输了!";
                }else {
                    alert("winner 响应错误!");
                    location.replace("/login.html");
                }
                // 增加一个按钮
                let backButton = document.createElement("button");
                backButton.innerHTML = "点击回到大厅";
                backButton.id = "backButton";
                let father = document.querySelector(".container>div");
                father.appendChild(backButton);
                backButton.onclick = function () {
                    location.replace("/game_hall.html");
                }
            }
        }else {
            alert("落子响应失败, 即将回到游戏大厅!");
            location.assign("/game_hall.html");
        }
    }
}

